package com.zlf.blog.controller;

import com.github.pagehelper.PageInfo;
import com.zlf.blog.dao.pojo.CommentVo;
import com.zlf.blog.service.ArticleService;
import com.zlf.blog.service.SysUserService;
import com.zlf.blog.utils.PageUtil;
import com.zlf.blog.utils.UserThreadLocal;
import com.zlf.blog.vo.*;
import com.zlf.blog.vo.params.PageParams;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * @author zlfi1
 */
@RestController
@RequestMapping("articles")
@Api(tags="文章")
@ApiOperation(value = "文章列表")
//@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ArticleController {
//    private final ArticleService articleService;
//    private final SysUserService sysUserService;
    @Autowired
    private ArticleService articleService;

    @Autowired
    private SysUserService sysUserService;
    ArticleController() {

    }

    /**
     * 首页文章列表
     * @param pageParams
     * @return
     */
    /**
     * Result是统一结果返回
     */
    @PostMapping("/all")
    public Result articles(@RequestBody(required = false) PageParams pageParams) {
        //ArticleVo 页面接收的数据
        return Result.success(articleService.listArticle(pageParams));
    }

    @GetMapping("/list")
    @ApiOperation("用户自己的Article")
    public Result userArticle(@Param("page")int page,@Param("size") int size){ //@RequestParam(value = "page", defaultValue = "0") int page,
                                                //@RequestParam(value = "size", defaultValue = "1") int size
        String id= UserThreadLocal.get().getId();
        List<ArticleVo> articleVoList=articleService.userArticle(id);
//        JSONArray jsonArray=new JSONArray();
//        jsonArray.addAll(articleService.userArticle(id));
        PageInfo pageInfo=PageUtil.startPage(articleVoList,page,size);
        return Result.success(pageInfo);
    }

    @PostMapping("/editId")
    @ApiOperation("点击编辑按钮")
    public Result editId(@RequestBody EditArticleVo editArticleVo){
        return Result.success(articleService.selectArticleBodyById(editArticleVo.getBodyId()));
    }

    @PostMapping("/updateArticle")
    @ApiOperation("更新Article")
    public Result updateArticle(@RequestBody EditArticleVo editArticleVo){
        return Result.success(articleService.updateArticleBodyById(editArticleVo));
    }

    @GetMapping("/deleteArticle")
    @ApiOperation("删除Article")
    public Result deleteArticle(@RequestParam("articleId")String articleId){
        return Result.success(articleService.deleteArticle(articleId));
    }

    @PostMapping("/addArticle")
    @ApiOperation("新增Article")
    public Result addArticle(@RequestBody ArticleAdd articleAdd){
        return Result.success(articleService.addArticle(articleAdd));
    }

    @ApiOperation("文件上传")
    @PostMapping("/uploadFile")
    public Result uploadFile(MultipartFile file,String paths) throws IOException {
        try{
            //path:目标目录
           File path=new File(paths);
            if(!path.exists()){
                path.mkdirs();
            }
            String oldName= file.getOriginalFilename();
            String fileId=UUID.randomUUID().toString().substring(0,18).replace("-","");
            String fileName= fileId +oldName.substring(oldName.lastIndexOf("."));
            String userAccount=UserThreadLocal.get().getAccount();
            File descFile=new File(path.getAbsoluteFile()+"/"+fileName);
            file.transferTo(descFile);
            articleService.uploadFile(fileId,fileName,userAccount);
            return Result.diy(200,"文件上传成功!",true,null);
        }
        catch (IOException e){
            e.printStackTrace();
            return Result.fail(100,"文件上传失败");
        }
    }

    @ApiOperation("文件下载")
    @GetMapping("/downloadFile")
    public ResponseEntity<Object> downloadFile(@RequestParam String fileName, HttpServletResponse response) throws IOException {
        File file = new File("D:\\java_study\\zlf-parent\\zlf-api\\src\\main\\resources\\static\\files\\"+fileName);
        InputStreamResource resource=new InputStreamResource(new FileInputStream((file)));
        HttpHeaders headers=new HttpHeaders();
        headers.add("Content-Disposition",String.format("attachment;filename=\"%s",fileName));
        headers.add("Cache-Control","no-cache,no-store,mush-revalidate");
        headers.add("Pragma","no-cache");
        headers.add("Expires","0");
        ResponseEntity<Object> responseEntity=ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/test"))
                .body(resource);
        System.out.println(responseEntity);
        return responseEntity;
        /**
         * 从服务器本地读取文件
         */
//        File file = new File("D:\\java_study\\zlf-parent\\zlf-api\\src\\main\\resources\\static\\files\\"+fileName.getFileName());
//        //判断文件是否存在
//        if(!file.exists()){
//            response.sendError(404,"你下载的资源不存在!!!");
//        }
//        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
//        //响应输出流
//        OutputStream outputStream = response.getOutputStream();
//        //设置响应头
//        response.setHeader("content-type", "application/octet-stream");
//        response.setContentType("application/octet-stream");
//        response.setCharacterEncoding("UTF-8");
//        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
//        //将文件以流的方式传给前端
//        int i = 0;
//        byte[] buff = new byte[1024];
//        while ((i = bis.read(buff)) != -1) {
//            outputStream.write(buff, 0, i);
//        }
//        bis.close();
//        outputStream.close();
//        System.out.println("下载成功！");
   }

    @GetMapping("/viewArticle")
    @ApiOperation("查看详情")
    public Result viewArticle(@RequestParam String articleId){
        return Result.success(articleService.selectArticleBodyByArticleId(articleId));
    }

    @PostMapping("/changeInfo")
    @ApiOperation("修改资料")
    public Result changeInfo(@RequestBody ChangeUserInfoVo changeUserInfoVo) {
        //String avatarUrl="D:\\java_study\\zlf-parent\\zlf-api\\src\\main\\resources\\static\\avatar";

        changeUserInfoVo.setId(UserThreadLocal.get ().getId());
        String id = changeUserInfoVo.getId();
        return Result.success(sysUserService.changeInfo(changeUserInfoVo, id));
    }

    @GetMapping("/comment")
    @ApiOperation("获取评论")
    public Result comment(@Param("bodyId") String bodyId){
        return Result.success(articleService.selectComment(bodyId));
    }

    @PostMapping("/addComment")
    @ApiOperation("添加评论")
    public Result addComment(@RequestBody(required = false) CommentVo commentVo){
        return Result.success(articleService.addComment(commentVo));
    }

    @PostMapping("/replyComment")
    @ApiOperation("回复评论")
    public Result replyComment(@RequestBody(required = false) CommentVo commentVo){
        return Result.success(articleService.replyComment(commentVo));
    }

}